import gulp from 'gulp';
import run from 'gulp-run';
import babel from 'gulp-babel';
import sourcemaps from 'gulp-sourcemaps';
import runSequence from 'run-sequence';
import replace from 'gulp-replace';
import fs from 'fs';

const settings = JSON.parse(fs.readFileSync('./package.json'));

const paths = {
    src: 'src',
    build: 'build',
    dest: 'dist',
    conf: 'conf',
};

gulp.task('build', () => {
    const ret = runSequence('replace',
                            'lint',
                            ['build-debug', 'build-online']);
    return ret;
});

gulp.task('build-debug', () => {
    const ret = runSequence('build-clean-debug',
                            'build-compile-debug');
    return ret;
});

gulp.task('build-online', () => {
    const ret = runSequence('build-clean-online',
                            'build-compile-online');
    return ret;
});

gulp.task('build-clean-online', () => {
    const ret = run(`rm -rf ${paths.dest}`).exec();
    return ret;
});

gulp.task('build-clean-debug', () => {
    const ret = run(`rm -rf ${paths.build}`).exec();
    return ret;
});

gulp.task('build-compile-online', () => {
    const ret = gulp.src(`${paths.src}/**/*.js`)
        .pipe(babel())
        .pipe(gulp.dest(paths.dest));
    return ret;
});

gulp.task('build-compile-debug', () => {
    const ret = gulp.src(`${paths.src}/**/*.js`)
        .pipe(sourcemaps.init())
        .pipe(babel())
        .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '../src' }))
        .pipe(gulp.dest(paths.build));
    return ret;
});

gulp.task('lint', () => {
    const ret = run(`eslint ${paths.src}`).exec();
    return ret;
});

gulp.task('replace', () => {
    const ret = gulp.src(`${paths.conf}/*`)
        .pipe(replace(/@NODE_VERSION@/g, settings.config.node_ver))
        .pipe(replace(/@REPO@/g, settings.config.repo))
        .pipe(replace(/@NAMESPACE@/g, settings.config.namespace))
        .pipe(replace(/@APP_NAME@/g, settings.name))
        .pipe(replace(/@APP_VERSION@/g, settings.version))
        .pipe(replace(/@SERVER_PORT@/g, settings.config.port))
        .pipe(gulp.dest('./'));
    return ret;
});
